package com.vf.cloud.rendering.server.relay;

import com.jfinal.kit.StrKit;
import com.vf.cloud.rendering.common.constant.Cache;
import com.vf.cloud.rendering.server.relay.server.StunServer;
import com.vf.cloud.rendering.server.relay.server.TurnServer;

public class RelayServer {

	private static volatile RelayServer INSYANCE;

	private TurnServer turn;
	
	private StunServer stun;
	

	private RelayServer() {
		turn = new TurnServer();
		stun= new StunServer();
	}

	public static RelayServer getInstance() {
		if (null == INSYANCE) {
			synchronized (RelayServer.class) {
				if (null == INSYANCE) {
					INSYANCE = new RelayServer();
				}
			}
		}
		return INSYANCE;
	}

	public void run() {
		if(verify()) {
			if(turn!=null) {
				turn.run();
			}
			
			if(stun!=null) {
				stun.run();
			}
		}
	}
	
	public void restart() {
		stop();
		run();
	}
	
	public void stop() {
		if(turn!=null) {
			turn.stop();
		}
		
		if(stun!=null) {
			stun.stop();
		}
	}
	
	public void destroy() {
		stop();
	}
	
	public boolean verify() {

		if (Cache.relay == null) {
			return false;
		}
		
		if(StrKit.isBlank(Cache.relay.getIp())) {
			return false;
		}
		if(StrKit.isBlank(Cache.relay.getStunPort())) {
			return false;
		}
		if(StrKit.isBlank(Cache.relay.getTurnPort())) {
			return false;
		}
		
		if(!StrKit.equals("1", Cache.relay.getEnabled())) {
			return false;
		}
		
		return true;
	}

	public int getStatus() {
		if (stun != null) {
			return stun.getStatus();
		}
		return -1;
	}
}

